import newInstance from './axios.util';
import responseCodeDeal from './linitly.response'
import { SYSTEM_CODE } from '@/constant/common/common'

import qs from 'qs'

newInstance.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
newInstance.defaults.headers.common['system_code'] = SYSTEM_CODE;
const TOKEN_KEY = 'token';
const REFRESH_TOKEN_KEY = 'refresh_token';
const REQUEST_URL_PREFIX = '/admin';

newInstance.interceptors.request.use(
  (config) => {
    // 设置token
    setTokenRequest(config)
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

newInstance.interceptors.response.use(
  (response) => {
    // 这里无论如何处理，最好返回一个Promise，正常的返回调用resolve方法，异常的调用reject
    // 这样业务代码里可以只处理正常流程而不用担心异常时会进入业务处理流程中，从而导致出错
    // 设置token
    setTokenLocal(response.headers)
    return responseCodeDeal(response.data);
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求时设置token的请求头
function setTokenRequest(config) {
  config.url = REQUEST_URL_PREFIX + config.url
  config.headers[TOKEN_KEY] = window.localStorage.getItem(TOKEN_KEY);
  config.headers[REFRESH_TOKEN_KEY] = window.localStorage.getItem(REFRESH_TOKEN_KEY);
}

// 相应时设置本地的token值
function setTokenLocal(headers) {
  if (headers && headers[TOKEN_KEY]) {
    window.localStorage.setItem(TOKEN_KEY, headers[TOKEN_KEY]);
  }
  if (headers && headers[REFRESH_TOKEN_KEY]) {
    window.localStorage.setItem(REFRESH_TOKEN_KEY, headers[REFRESH_TOKEN_KEY]);
  }
}

const postJson = (url, data) => {
  return newInstance.post(url, data)
};

const postPaginationJson = (url, requestParams) => {
  return newInstance.request({
    url,
    params: {
      pageNumber: requestParams.pageNumber,
      pageSize: requestParams.pageSize
    },
    data: requestParams.data,
    method: 'post'
  })
}

const postForm = (url, params) => {
  return newInstance.post(url, qs.stringify(params), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

const uploadSingleImage = (options) => {
  let datas = new FormData()
  datas.append('file', options.file)
  return newInstance.post('/file/upload/image', datas, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

export { postJson, postPaginationJson, postForm, uploadSingleImage }
